package com.twu.biblioteca;

import com.twu.biblioteca.command.*;
import com.twu.biblioteca.db.BookStore;
import com.twu.biblioteca.db.MovieStore;
import com.twu.biblioteca.db.UserStore;
import com.twu.biblioteca.model.User;
import com.twu.biblioteca.utilities.ConsoleReader;
import com.twu.biblioteca.utilities.MessagePrinter;

import java.util.HashMap;
import java.util.Map;

public class BibliotecaApp {
    private static User LOGGED_IN_USER;
    private BookStore bookStore;
    private MovieStore movieStore;
    private UserStore userStore;
    private MessagePrinter printer;
    private ConsoleReader reader;
    private Map<Integer,Command> commandMap;

    public BibliotecaApp() {
        this.bookStore = new BookStore();
        this.movieStore = new MovieStore();
        this.userStore = new UserStore();
        this.printer = new MessagePrinter();
        this.reader = new ConsoleReader();
    }

    public static void main(String[] args) {
        BibliotecaApp app = new BibliotecaApp();
        int choice;
        Command selectedCommand;
        app.printer.printWelcomeMessage();
        do {
            if(LOGGED_IN_USER == null) {
                app.login();
                choice = -1;
            }
            else {
                app.printer.printMenu();
                choice = app.reader.readChoice();
                selectedCommand = app.commandMap.get(choice);
                if(selectedCommand == null)
                    System.out.println("Invalid choice!");
                else
                    selectedCommand.execute();
            }
        }while(choice!=0);
    }

    private void login() {
        String libraryNumber = reader.readFromConsole("Library number");
        String password = reader.readFromConsole("Password");
        User user = userStore.findUserById(libraryNumber);
        if(user!=null && user.verifyPassword(password)) {
            LOGGED_IN_USER = user;
            initializeCommandMap();
            printer.printSuccessLoginMessage();
        }
        else
            printer.printErrorLoginMessage();
    }

    private void initializeCommandMap(){
        commandMap = new HashMap<Integer, Command>();
        commandMap.put(1,new ListBooksCommand(bookStore));
        commandMap.put(2,new CheckoutBookCommand(LOGGED_IN_USER,printer,bookStore,reader));
        commandMap.put(3,new ReturnBookCommand(bookStore,reader,printer));
        commandMap.put(4,new ListMovieCommand(movieStore));
        commandMap.put(5,new CheckoutMovieCommand(movieStore,printer,reader));
        commandMap.put(6, new WhoCheckedOutBookCommand(bookStore,reader));
        commandMap.put(7,new PrintUserInfoCommand(LOGGED_IN_USER));
        commandMap.put(0,new QuitCommand());
    }

}
